package com.demo.scenic.shiro;

import com.demo.scenic.domain.Role;
import com.demo.scenic.domain.User;
import com.demo.scenic.service.UserService;
import com.demo.scenic.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;
    /**
     * 为了表明支持的时jwtToken,而非别的Token，需要进行一个判断，即return的语句，说明支持才能进行强转
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        AccountProfile principal = (AccountProfile) principalCollection.getPrimaryPrincipal();
        //根据住身份信息获取角色和权限信息
        //授权角色信息
        List<Role> roleList = userService.findRolesByUserId(principal.getId());
        if (!CollectionUtils.isEmpty(roleList)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roleList.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getRoleName());
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String mobile = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        User user = userService.findByMobile(mobile);
        if(ObjectUtils.isEmpty(user)){
            throw  new UnknownAccountException("用户不存在");
        }
        AccountProfile profile = new AccountProfile();
        profile.setId(user.getId());
        profile.setMobile(user.getMobile());
        profile.setAvatar(user.getAvatar());
        profile.setUsername(user.getUsername());
        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
